@using BTCPayServer.Client.Models
@using BTCPayServer.Payouts
@using BTCPayServer.Views.Stores
@using BTCPayServer.Client
@model BTCPayServer.Models.WalletViewModels.PayoutsModel

@inject PayoutMethodHandlerDictionary PayoutHandlers;
@{
    var storeId = Context.GetRouteValue("storeId") as string;
    ViewData.SetLayoutModel(new(nameof(StoreNavPages.Payouts), string.IsNullOrEmpty(Model.PullPaymentName) ? StringLocalizer["Payouts"] : StringLocalizer["Payouts for pull payment {0}", Model.PullPaymentName]));
    Model.PaginationQuery ??= new Dictionary<string, object>();
    Model.PaginationQuery.Add("pullPaymentId", Model.PullPaymentId);
    Model.PaginationQuery.Add("payoutMethodId", Model.PayoutMethodId);
    Model.PaginationQuery.Add("payoutState", Model.PayoutState);
    var stateActions = new List<(string Action, string Text)>();
    if (PayoutMethodId.TryParse(Model.PayoutMethodId, out var payoutMethodId))
    {
		var payoutHandler = PayoutHandlers.TryGet(payoutMethodId);
        if (payoutHandler is null)
            return;
        stateActions.AddRange(payoutHandler.GetPayoutSpecificActions().Where(pair => pair.Key == Model.PayoutState).SelectMany(pair => pair.Value));
    }

    switch (Model.PayoutState)
    {
        case PayoutState.AwaitingApproval:
            if (!Model.HasPayoutProcessor) stateActions.Add(("approve-pay", StringLocalizer["Approve & Send"]));
            stateActions.Add(("approve", StringLocalizer["Approve"]));
            stateActions.Add(("cancel", StringLocalizer["Cancel"]));
            break;
        case PayoutState.AwaitingPayment:
            if (!Model.HasPayoutProcessor) stateActions.Add(("pay", StringLocalizer["Send"]));
            stateActions.Add(("cancel", StringLocalizer["Cancel"]));
            stateActions.Add(("mark-paid", StringLocalizer["Mark as already paid"]));
            break;
		case PayoutState.InProgress:
			stateActions.Add(("mark-awaiting-payment", StringLocalizer["Mark as awaiting payment"]));
			break;
    }
}

@section PageHeadContent {
    <style>
        #Payouts .badge.rounded-pill {
            font-size: var(--btcpay-font-size-s);
            color: inherit;
        }
    </style>
}

@section PageFootContent {
    <script>
        delegate('click', '.selectAll', e => {
            const { payoutState } = e.target.dataset;
            document.querySelectorAll(`.selection-item-${payoutState}`).forEach(checkbox => {
                checkbox.checked = e.target.checked;
            });
        });
    </script>
}

<div class="sticky-header">
    <h2 class="my-1">
        @ViewData["Title"]
        <a href="#descriptor" data-bs-toggle="collapse">
            <vc:icon symbol="info" />
        </a>
    </h2>
</div>

<div id="descriptor" class="collapse">
    <div class="d-flex px-4 py-4 mb-4 bg-tile rounded">
        <div class="flex-fill">
            <p class="mb-3">
                <span text-translate="true">Payouts allow you to process pull payments, in the form of refunds, salary payouts, or withdrawals.</span>
                <span permission="@Policies.CanModifyStoreSettings">You can also <a id="PayoutProcessors" asp-action="ConfigureStorePayoutProcessors" asp-controller="UIPayoutProcessors" asp-route-storeId="@storeId">configure payout processors</a> to automate payouts.</span>
            </p>
            <a href="https://docs.btcpayserver.org/Payouts/" target="_blank" rel="noreferrer noopener" text-translate="true">Learn More</a>
        </div>
        <button type="button" class="btn-close ms-auto" data-bs-toggle="collapse" data-bs-target="#descriptor" aria-expanded="false" aria-label="@StringLocalizer["Close"]">
            <vc:icon symbol="close" />
        </button>
    </div>
</div>

<partial name="_StatusMessage" />

@if (!Model.HasPayoutProcessor)
{
    <div class="alert alert-info mb-5" role="alert" permission="@Policies.CanModifyStoreSettings">
        <span text-translate="true">Pro tip: There are supported but unconfigured Payout Processors for this payout payment method.</span><br/>
        <span text-translate="true">Payout Processors help automate payouts so that you do not need to manually handle them.</span>
        <a class="alert-link p-0" asp-action="ConfigureStorePayoutProcessors" asp-controller="UIPayoutProcessors" asp-route-storeId="@storeId" text-translate="true">Configure now</a>
    </div>
}

<form method="post" id="Payouts">
    <input type="hidden" asp-for="PayoutMethodId" />
    <input type="hidden" asp-for="PayoutState" />
    <div class="d-flex justify-content-between mb-4">
        <ul class="nav mb-1 gap-2">
            @foreach (var state in Model.PayoutMethods)
            {
                <li class="nav-item py-0">
                    <a asp-action="Payouts" asp-route-storeId="@Context.GetRouteValue("storeId")"
                       asp-route-payoutState="@Model.PayoutState"
                       asp-route-payoutMethodId="@state.ToString()"
                       asp-route-pullPaymentId="@Model.PullPaymentId"
                       class="btcpay-pill position-relative me-0 @(state.ToString() == Model.PayoutMethodId ? "active" : "")"
                       id="@state.ToString()-view"
                       role="tab">
                        @state.ToString()
                        @if (Model.PayoutMethodCount.TryGetValue(state.ToString(), out var count) && count > 0)
                        {
                            <span class="badge rounded-pill fw-semibold pe-0">@count</span>
                        }
                    </a>
                </li>
            }
        </ul>
    </div>
    <nav id="SectionNav" class="mb-3">
        <div class="nav">
            @foreach (var state in Model.PayoutStateCount)
            {
                <a id="@state.Key-view"
                   asp-action="Payouts"
                   asp-route-storeId="@Context.GetRouteValue("storeId")"
                   asp-route-payoutState="@state.Key"
                   asp-route-pullPaymentId="@Model.PullPaymentId"
                   asp-route-payoutMethodId="@Model.PayoutMethodId"
                   class="nav-link @(state.Key == Model.PayoutState ? "active" : "")" role="tab">
                    @state.Key.GetStateString()
                    @if (state.Value > 0)
                    {
                        <span class="badge rounded-pill fw-semibold ms-1 bg-medium">@state.Value</span>
                    }
                </a>
            }
        </div>
    </nav>
    @if (Model.Payouts.Any())
    {
        <div class="table-responsive">
            <table class="table table-hover mass-action">
                <thead class="mass-action-head">
                    <tr>
                        @if (stateActions.Any())
                        {
                            <th class="only-for-js mass-action-select-col" permission="@Policies.CanManagePayouts">
                                <input type="checkbox" class="form-check-input mass-action-select-all" data-payout-state="@Model.PayoutState.ToString()" />
                            </th>
                        }
                        <th class="date-col">
                            <div class="d-flex align-items-center gap-3">
                                <span text-translate="true">Date</span>
                                <button type="button" class="btn btn-link p-0 switch-time-format only-for-js" title="Switch date format">
                                    <vc:icon symbol="time" />
                                </button>
                            </div>
                        </th>
                        <th text-translate="true">Source</th>
                        <th text-translate="true">Destination</th>
                        <th text-translate="true" class="amount-col">Amount</th>
                        @if (Model.PayoutState != PayoutState.AwaitingApproval)
                        {
                            <th text-translate="true" class="text-end">Transaction</th>
                        }
                    </tr>
                </thead>
                @if (stateActions.Any())
                {
                    <thead class="mass-action-actions" permission="@Policies.CanManagePayouts">
                    <tr>
                        <th class="mass-action-select-col only-for-js">
                            <input type="checkbox" class="form-check-input mass-action-select-all" />
                        </th>
                        <th colspan="5">
                            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3">
                                <div>
                                    <strong class="mass-action-selected-count">0</strong>
                                    <span text-translate="true">selected</span>
                                </div>
                                <div class="d-inline-flex align-items-center gap-3">
                                    @foreach (var action in stateActions)
                                    {
                                        <button type="submit" id="@Model.PayoutState-@action.Action" name="Command" class="btn btn-link" value="@Model.PayoutState-@action.Action">@action.Text</button>
                                    }
                                </div>
                            </div>
                        </th>
                    </tr>
                    </thead>
                }
                <tbody>
                    @for (var i = 0; i < Model.Payouts.Count; i++)
                    {
                        var pp = Model.Payouts[i];
                        <tr class="payout mass-action-row">
                            @if (stateActions.Any())
                            {
                                <td class="only-for-js mass-action-select-col align-middle" permission="@Policies.CanManagePayouts">
                                    <input type="checkbox" class="selection-item-@Model.PayoutState.ToString() form-check-input mass-action-select" asp-for="Payouts[i].Selected" />
                                    <input type="hidden" asp-for="Payouts[i].PayoutId" />
                                </td>
                            }
                            <td class="date-col align-middle">
                                @pp.Date.ToBrowserDate()
                            </td>
                            <td class="align-middle">
                                @if (pp.SourceLink is not null && pp.Source is not null)
                                {
                                    <a href="@pp.SourceLink" rel="noreferrer noopener">@pp.Source</a>
                                }
                                else if (pp.Source is not null)
                                {
                                    <span>@pp.Source</span>
                                }
                            </td>
                            <td class="align-middle">
                                <vc:truncate-center text="@pp.Destination" classes="truncate-center-id" />
                            </td>
                            <td class="amount-col align-middle">
                                <span data-sensitive>@pp.Amount</span>
                            </td>
                            @if (Model.PayoutState != PayoutState.AwaitingApproval)
                            {
                                <td class="text-end align-middle">
                                    @if (!string.IsNullOrEmpty(pp.ProofLink))
                                    {
                                        <a class="transaction-link" href="@pp.ProofLink" rel="noreferrer noopener" text-translate="true">Link</a>
                                    }
                                </td>
                            }
                        </tr>
                    }
                </tbody>
            </table>
        </div>
        <vc:pager view-model="Model" />
    }
    else
    {
        <p class="text-muted mb-0" id="@Model.PayoutState-no-payouts" text-translate="true">There are no payouts matching these criteria.</p>
    }
</form>
